package com.ujiuye.utils;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: zwp
 * @version: 1.0
 * @create 2021-07-07 14:15
 */
/*
把文件上传的代码写这里来
 */
public class MyFileUtils {
    //上传
    public static File upload(MultipartFile multipartFile,String path){
        //获取上传文件的名称   原本的文件名字
        String filename = multipartFile.getOriginalFilename();
        String newName = getName(filename);
        //创建文件对象    这个文件现在还是空的
        File file = new File(path+newName);
        //springmvc接收到的用户上传的文件内容是保存在内存中  把内存中的数据写到刚刚新建的文件中
        try {
            multipartFile.transferTo(file);
            return file;
        } catch (IOException e) {
            return null;
        }
    }

    //名字的算随你定
    private static String getName(String filename) {
        String suufixName=filename.substring(filename.lastIndexOf("."));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        //生成4位随机数
        String random = String.valueOf(Math.random()).substring(3, 7);
        String format = dateFormat.format(new Date());
        return format+random+suufixName;
    }

    //下载
    public static ResponseEntity<byte[]> download(File file) throws IOException {
        byte[] bytes = FileUtils.readFileToByteArray(file);
        HttpHeaders httpHeaders = new HttpHeaders();
        String newName = new String(file.getName().getBytes("utf-8"),"ISO-8859-1");
        httpHeaders.setContentDispositionFormData("attchment",newName);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes,httpHeaders, HttpStatus.OK);
    }
}
